package org.yylnb.openplatform.commons.utlis;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author RainLin
 * @date 2020/7/28 - 20:36
 */
public class HttpUtil {
    private static final String ENCODING = "utf-8";


    /**
     * 发起请求的工具类
     *
     * @param urlStr      请求地址
     * @param data        请求的数据
     * @param contentType 内容格式
     */
    public static String postData(String urlStr, String data, String contentType, String method) {

        try {
            URL url = new URL(urlStr);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            if (method != null) {
                //默认是get
                urlConnection.setRequestMethod(method);
            }
            //允许向外发送数据
            urlConnection.setDoOutput(true);
            //允许接收服务器返回的数据
            urlConnection.setDoInput(true);

            if (contentType != null) {
                //设置请求头
                urlConnection.setRequestProperty("content-type", contentType);
            }

            if (data != null) {
                OutputStream outputStream = urlConnection.getOutputStream();
                OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, ENCODING);
                outputStreamWriter.write(data);
                outputStreamWriter.flush();
                outputStreamWriter.close();
            }
            //获取输入流
            InputStream inputStream = urlConnection.getInputStream();

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line = null;
            StringBuffer stringBuffer = new StringBuffer();
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
            }
            bufferedReader.close();

            return stringBuffer.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


}

